package edu.iiitb.studentinfo.service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import edu.iiitb.studentinfo.model.*;
import edu.iiitb.studentinfo.util.DBconn;

public class StudentSearchService {
	
	private DBconn dbconn = null;
	private Connection con = null;
	private PreparedStatement pst = null;
	private Statement stmt = null;
	private ResultSet resultSet = null;
	private String query = null;
	
	
	public ArrayList<Friend> getStudents(String searchString) {
		ArrayList<Friend> students = new ArrayList<Friend>();
		
		query = "SELECT studentid, firstName, lastName, RollNo FROM student_information WHERE (firstName like ?) OR (lastName like ?) ";
		
		try {
			dbconn = new DBconn();
			con = dbconn.getConnection();
			pst = con.prepareStatement(query);
			pst.setString(1, "%" + searchString + "%");
			pst.setString(2, "%" + searchString + "%");
			
			
			resultSet = pst.executeQuery();
			
			
			while(resultSet.next()) {
				Friend student = new Friend();
				
				student.setFirstName(resultSet.getString("firstName"));
				student.setStudentid(resultSet.getInt("studentid"));
				student.setLastName(resultSet.getString("lastName"));
				student.setRollNo(resultSet.getString("RollNo"));

				students.add(student);
			}
			
			
		} catch (SQLException e) {
			System.out.println(e.getMessage());
			
		} finally {
			dbconn.close(resultSet);
			dbconn.close(pst);
			dbconn.close(con);
		}
		
		return students;
	}

}
